package com.fish.admin.module.system.service.impl;

import com.fish.admin.module.auth.domain.entity.AuthInfo;
import com.fish.admin.module.auth.manager.AuthInfoManager;
import com.fish.admin.module.system.domain.dto.SysUserDTO;
import com.fish.admin.module.system.domain.dto.SysUserPageQueryDTO;
import com.fish.admin.module.system.domain.entity.SysUser;
import com.fish.admin.module.system.domain.vo.SysUserVO;
import com.fish.admin.module.system.manager.SysUserManager;
import com.fish.admin.module.system.service.SysUserService;
import com.fish.admin.module.system.validator.SystemValidator;
import com.fish.common.core.domain.vo.PageVO;
import com.fish.common.core.enums.EnabledEnum;
import com.fish.common.core.enums.ReadonlyEnum;
import com.fish.common.core.enums.StatusEnum;
import com.fish.common.core.enums.UserTypeEnum;
import com.fish.common.mybatisplus.util.PageUtils;
import com.fish.common.support.util.BeanHelpers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class SysUserServiceImpl implements SysUserService {

    private final SysUserManager sysUserManager;

    private final AuthInfoManager authInfoManager;
    @Override
    public PageVO<SysUserVO> page(SysUserPageQueryDTO sysUserPageQueryDTO) {
       return PageUtils.toPage(sysUserManager.page(sysUserPageQueryDTO));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserDTO sysUserDTO) {
        //新增用户
        SysUser sysUser = new SysUser();
        BeanHelpers.copyProperties(sysUserDTO, sysUser);
        sysUser.setReadonly(ReadonlyEnum.YES.getValue());
        sysUser.setStatus(StatusEnum.YES.getValue());
        sysUserManager.save(sysUser);

        //新增账号
        AuthInfo authInfo = new AuthInfo();
        authInfo.setAccount(sysUserDTO.getAccount());
        authInfo.setSecret(sysUserDTO.getSecret());
        authInfo.setUserId(sysUser.getId());
        authInfo.setUserType(UserTypeEnum.SYSTEM.getValue());
        authInfo.setEnabled(EnabledEnum.YES.getValue());
        authInfo.setStatus(StatusEnum.YES.getValue());
        authInfo.setReadonly(ReadonlyEnum.YES.getValue());
        authInfoManager.save(authInfo);
    }

    @Override
    public void deleteById(Long id) {
        SystemValidator.validateUser(id);
        sysUserManager.deleteById(id);
    }

    @Override
    public void updateById(Long id, SysUserDTO sysUserDTO) {
        SystemValidator.validateUser(id);
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setRoleId(sysUserDTO.getRoleId());
        sysUser.setRemark(sysUserDTO.getRemark());
        sysUserManager.updateById(sysUser);
    }


}
